package com.leyou.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.leyou.controller.UploadController;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;


/**
 * *
 * Created by IntelliJ IDEA.
 * Author: caoLei
 * Date: 2018/10/23
 * Time: 22:48
 * *
 */
@Service
public class UploadService {

    private static final Logger logger = LoggerFactory.getLogger(UploadController.class);

    //支持的文件类型
    private static final List<String> suffixes = Arrays.asList("image/png", "image/jpeg","image/jpg");

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    public String uploadImage(MultipartFile file) {
        try {
            //获取原始文件名
            String originalFilename = file.getOriginalFilename();
         //   StringUtils.substringAfterLast(originalFilename, ",");  另一种方法
            String type = file.getContentType();
            //校验文件类型
            if (!suffixes.contains(type)) {
                logger.info("上传失败，文件类型不匹配：{}", type);
                return null;
            }
            //校验文件内容
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image == null) {
                logger.info("上传失败，文件内容不符合要求");
                return null;
            }
            //保存图片
           // file.transferTo(new File("D:\\image\\" + originalFilename));  改造代码，之前是保存到本地，现在是保存到fastDES。
            String extension = StringUtils.substringAfterLast(originalFilename, ".");
            StorePath storePath = this.fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), extension, null);

            //拼接图片地址
            String url = "http://image.leyou.com/" + storePath.getFullPath();  //事先配置nginx配置文件
            return url;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
